﻿using System.Collections.Generic;
using System.IO;
using CloudShot.Core.Interfaces;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CloudShot.Services
{
  public class JsonConfiguration : IConfiguration
  {
    private readonly string _configFile;

    public JsonConfiguration(string configFile)
    {
      _configFile = configFile;
    }

    #region Work with config

    private Dictionary<string, JToken> _configurationSections;

    private static Dictionary<string, JToken> ReadConfiguration(string configFile)
    {
      Dictionary<string, JToken> result = null;

      var configInfo = new FileInfo(configFile);

      if (configInfo.Exists && configInfo.Length > 0)
      {
        string json = File.ReadAllText(configFile);
        result = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(json);
      }

      return result ?? new Dictionary<string, JToken>();
    }

    private static void WriteConfiguration(string configFile, Dictionary<string, JToken> configurationSections)
    {
      string json = JsonConvert.SerializeObject(configurationSections, Formatting.Indented);
      File.WriteAllText(configFile, json);
    }

    #endregion

    #region IConfiguration Implementation

    public IConfigurationSection GetConfigurationSection(string sectionName)
    {
      if (_configurationSections == null)
        _configurationSections = ReadConfiguration(_configFile);

      return new ConfigurationSection(sectionName, this);
    }

    public T GetSectionValue<T>(string sectionName)
    {
      if (!_configurationSections.ContainsKey(sectionName))//TODO: maybe here we should create sections if they are not exist?
        return default(T);

      JToken value = _configurationSections[sectionName];
      T result = value.ToObject<T>();
      return result;
    }

    public void WriteSectionValue<T>(string sectionName, T value)
    {
      JToken valueToSave = null;

      if (!Equals(value, default(T)))
        valueToSave = JToken.FromObject(value);  

      _configurationSections[sectionName] = valueToSave;

      WriteConfiguration(_configFile, _configurationSections);
    }

    #endregion
  }
}